/**
 * indexDB的执行操作都是异步的,
 * 存储不涉及浏览器的Document，可以配合Web Worker使用
 */

async function initDB(db, storeName) {
  return new Promise((resolve, reject) => {
    const request = indexedDB.open(db);

    // 数据库版本变更或第一次创建时触发
    request.onupgradeneeded = (event) => {
      const db = event.target.result;
      if (!db.objectStoreNames.contains(storeName)) {
        const store = db.createObjectStore(storeName, {
          keyPath: "id", // 主键 自增
          autoIncrement: true,
        });
        // 创建索引，加快查询速度
        store.createIndex("fileId", "fileId", { unique: false });
        store.createIndex("status", "status", { unique: false });
      }
    };

    request.onsuccess = () => resolve(request.result);
    request.onerror = () => reject(request.error);
  });
}

export default class BaseDB {
  constructor(dbName, storeName) {
    this.dbName = dbName;
    this.storeName = storeName;
    this.dbPromise = initDB(dbName, storeName);
  }

  async getStore(mode = "readwrite") {
    return new Promise(async (resolve, reject) => {
      const db = await this.dbPromise;
      const transaction = db.transaction(this.storeName, mode);
      const store = transaction.objectStore(this.storeName);
      resolve(store);
    });
  }

  getAllData() {
    return new Promise((resolve, reject) => {
      this.getStore().then((store) => {
        // 查询所有
        // const request = store.getAll();
        // 根据ID查询 / 返回具体对象值 无则undefined
        // const request = store.get(id);
        // 根据索引查询
        // const index = store.index(indexName);
        // const request = index.get(value);
        const request = store.getAll();
        request.onsuccess = () => resolve(request.result);
        request.onerror = (event) => reject(event.target.error);
      });
    });
  }

  addData(data) {
      // 1. 在事务外准备数据, file文件类的数据
    // const buffers = await Promise.all(
    //   chunks.map((chunk) => chunk.chunk.arrayBuffer())
    // );
    return new Promise((resolve, reject) => {
      this.getStore().then((store) => {
        const request = store.add(data);
        request.onsuccess = () => resolve("数据添加成功");
        request.onerror = (event) => reject(event.target.error);
      });
    });
  }

  // 先查询 再修改 且unique需要是false
  updateData(data) {
    return new Promise((resolve, reject) => {
      this.getStore().then((store) => {
        const index = store.index("fileId");
        const request = index.get(data.fileId);
        request.onsuccess = () => {
          const existing = request.result;
          existing.age = data.age;
          const request1 = store.put(existing);
          request1.onsuccess = () => resolve("数据更新成功");
          request1.onerror = (event) => reject(event.target.error);
        };
      });
    });
  }

  // 根据id删除
  deleteData(id) {
    return new Promise((resolve, reject) => {
      this.getStore().then((store) => {
        const request = store.delete(id);
        request.onsuccess = () => resolve("数据已删除");
        request.onerror = (event) => reject(event.target.error);
      });
    });
  }

  clearStore() {
    return new Promise((resolve, reject) => {
      this.getStore().then((store) => {
        const request = store.clear();
        request.onsuccess = () => resolve("表清空");
        request.onerror = (event) => reject(event.target.error);
      });
    });
  }
}
